/*
 * @Author: error: error: git config user.name & please set dead value or install git && error: git config user.email & please set dead value or install git & please set dead value or install git
 * @Date: 2025-05-15 16:52:31
 * @LastEditors: error: error: git config user.name & please set dead value or install git && error: git config user.email & please set dead value or install git & please set dead value or install git
 * @LastEditTime: 2025-05-15 20:06:55
 * @FilePath: \vite-project\vite.config.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { fileURLToPath, URL } from 'node:url'
import fsExtra from 'fs-extra'

import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'
import vueDevTools from 'vite-plugin-vue-devtools'
import tailwindcss from '@tailwindcss/vite'

import { defineConfig, loadEnv, PluginOption } from 'vite'
// legacy这里有版本的坑，如果是2.x版本，打包会报错
import legacy from '@vitejs/plugin-legacy'
// import MarkdownItAnchor from 'markdown-it-anchor'
// import MarkdownItPrism from 'markdown-it-prism'
// import Markdown from 'unplugin-vue-markdown/vite'
// import MarkdownPreview from 'vite-plugin-markdown-preview'
import { visualizer } from 'rollup-plugin-visualizer'

import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
import * as path from 'path'
import Components from 'unplugin-vue-components/vite'
import AutoImport from 'unplugin-auto-import/vite'
// mock服务
import { viteMockServe } from 'vite-plugin-mock'

import autoConfig from './plugins/autoConfig'

export default ({ mode }) => {
  // loadEnv不加第三个参数的话，只返回 VITE_ 开头的环境变量
  const env = loadEnv(mode, process.cwd(), '')
  const isNeedBuildAnalysis = env.VITE_APP_BUILD_ANALYSIS && env.VITE_APP_BUILD_ANALYSIS === 'true'
  return defineConfig({
    base: './',
    build: {
      sourcemap: true,
      minify: false,
    },
    server: {
      port: 3000,
      // shuai: 代理通过autoConfig插件自动生成了
      proxy: {},
    },
    plugins: [
      // vue(),
      vue({ include: [/\.vue$/, /\.md$/] }),
      vueJsx(),
      vueDevTools(),
      legacy({
        targets: ['Chrome 63'],
        additionalLegacyPolyfills: ['regenerator-runtime/runtime'],
        modernPolyfills: true,
      }),

      viteMockServe({
        // ↓忽略以_开头的文件
        ignore: /^_/,
        // ↓解析根目录下的mock文件夹
        mockPath: 'mock',
        enable: true, // 开发打包开关
        // prodEnabled: false, // 生产打包开关
        // supportTs: true, // 打开后，可以读取 ts 文件模块。 请注意，打开后将无法监视.js 文件。
        watchFiles: true, // 监视文件更改
        // 这个属性是给生产用的，也就是说prodEnabled必须是true才有用
        // injectCode: `
        //   import {setupProdMockServer} from '@/../mock/mockProdServer.ts';
        //   setupProdMockServer();
        // `,
        logger: true, //是否在控制台显示请求日志
      }),
      tailwindcss(),
      createSvgIconsPlugin({
        // 指定需要缓存的图标文件夹, 有顺序要求，先写子文件夹，后父文件夹
        // iconDirs: [
        // path.resolve(process.cwd(), 'src/icons/remix-icon/Buildings/'),
        // path.resolve(process.cwd(), 'src/icons/'),
        // ],
        iconDirs: [
          ...findDeepFolders(path.resolve(process.cwd(), 'src/icons')).sort(
            (a, b) => b.split('/').length - a.split('/').length,
          ),
        ],
        // 指定symbolId格式
        symbolId: 'icon-[dir]-[name]',

        /**
         * 自定义插入位置
         * @default: body-last
         */
        // inject?: 'body-last' | 'body-first'

        /**
         * custom dom id
         * @default: __svg__icons__dom__
         */
        customDomId: '__svg__icons__dom__',
      }),
      autoConfig(),
      Components({
        // dirs: ['src/**/*'],
        dirs: ['src/components/@hz', 'src/components'],
        directoryAsNamespace: true,
        collapseSamePrefixes: false,
      }),
      AutoImport({
        exclude: ['./src/env.d.ts'],
        // targets to transform
        include: [
          /\.[tj]sx?$/, // .ts, .tsx, .js, .jsx
          /\.vue$/,
          /\.vue\?vue/, // .vue
          /\.md$/, // .md
        ],
        // global imports to register
        imports: [
          // presets
          'vue',
          'vue-router',
          'pinia',
          // '@vueuse/core',
          // custom
          {
            '@vueuse/core': [
              // named imports
              'useMouse', // import { useMouse } from '@vueuse/core',
              'useVModels',
              // alias
              ['useFetch', 'useMyFetch'], // import { useFetch as useMyFetch } from '@vueuse/core',
            ],
            axios: [
              // default imports
              ['default', 'axios'], // import { default as axios } from 'axios',
            ],
            // '[package-name]': [
            // '[import-names]',
            // // alias
            // ['[from]', '[alias]'],
            // ],
          },
        ],
        // Auto import for module exports under directories
        // by default it only scan one level of modules under the directory
        dirs: [
          './src/utils/toolsAutoImport',
          // './hooks',
          // './composables' // only root modules
          // './composables/**', // all nested modules
          // ...
        ],

        // Filepath to generate corresponding .d.ts file.
        // Defaults to './auto-imports.d.ts' when `typescript` is installed locally.
        // Set `false` to disable.
        dts: './auto-imports.d.ts',

        // Auto import inside Vue template
        // see https://github.com/unjs/unimport/pull/15 and https://github.com/unjs/unimport/pull/72
        vueTemplate: false,
        // Custom resolvers, compatible with `unplugin-vue-components`
        // see https://github.com/antfu/unplugin-auto-import/pull/23/
        resolvers: [
          /* ... */
        ],
        // Generate corresponding .eslintrc-auto-import.json file.
        // eslint globals Docs - https://eslint.org/docs/user-guide/configuring/language-options#specifying-globals
        eslintrc: {
          enabled: true, // Default `false`
          filepath: './.eslintrc-auto-import.json', // Default `./.eslintrc-auto-import.json`
          globalsPropValue: true, // Default `true`, (true | false | 'readonly' | 'readable' | 'writable' | 'writeable')
        },
        /* options */
      }),
      visualizer({
        filename: './dist/stats.html', // 分析报告的输出文件
        open: true, // 在完成后自动打开报告
        gzipSize: true, // 显示gzip后的体积
        brotliSize: true, // 显示brotli后的体积
      }),

      // Markdown({
      //   headEnabled: true,
      //   frontmatter: true, // 确保启用 frontmatter 支持
      //   markdownItOptions: {
      //     html: true,
      //     linkify: true,
      //     typographer: true,
      //   },

      //   markdownItSetup(md) {
      //     // for example
      //     md.use(MarkdownItAnchor)
      //     md.use(MarkdownItPrism, { highlightInlineCode: true, defaultLanguage: 'html' })
      //   },
      // }),
      // MarkdownPreview(),
    ],
    resolve: {
      extensions: ['.mjs', '.js', '.ts', '.jsx', '.tsx', '.json', '.vue'],
      alias: {
        '@/': new URL('./src/', import.meta.url).pathname,
        '@antv/x6': '@antv/x6/lib',
        '@antv/x6-vue-shape': '@antv/x6-vue-shape/lib',
      },
    },
  })
}

// https://vite.dev/config/
// export default defineConfig({
//   plugins: [
//     vue(),

//     // vueJsx(),
//     vueDevTools(),
//   ],
//   resolve: {
//     alias: {
//       '@': fileURLToPath(new URL('./src', import.meta.url)),
//     },
//   },
// })

// 递归获取文件夹下所有子文件夹
const findDeepFolders = (dirPath) => {
  const result = [dirPath]
  const contents = fsExtra.readdirSync(dirPath)
  contents.forEach((cur) => {
    const curPath = `${dirPath}/${cur}`
    if (fsExtra.lstatSync(curPath).isDirectory()) {
      result.push(...findDeepFolders(curPath))
    }
  })
  return result
}
